package com.ly.jvm;
import java.io.*;

/**
 * @Classname MyClassLoader
 * @Description TODO
 * @Date 2020/10/28 16:22
 * @Author 冷心影翼
 */
public class MyClassLoader extends ClassLoader {

	private String byteCodePath;

	public MyClassLoader(String byteCodePath) {
		this.byteCodePath = byteCodePath;
	}

	public MyClassLoader(ClassLoader classLoader,String byteCodePath) {
		super(classLoader);
		this.byteCodePath = byteCodePath;
	}

	public static void main(String[] args) {
		MyClassLoader myClassLoader = new MyClassLoader("F:\\IdeaCode\\frame\\interview\\target\\classes\\com\\ly\\test\\");

		try{
			Class<?> aClass = myClassLoader.loadClass("T");
			System.out.println(aClass.getClassLoader().getClass().getClassLoader().getClass().getName());
		}catch(Exception e){

		}finally {

		}

	}

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		String filename = byteCodePath + name + ".class";
		BufferedInputStream bis = null;
		ByteArrayOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(new File(filename)));
			bos = new ByteArrayOutputStream();

			int len;
			byte[] data = new byte[1024];
			while ((len = bis.read(data))!=-1) {
				bos.write(data,0,len);
			}

			byte[] bytes = bos.toByteArray();
			Class clazz = defineClass(null,bytes,0,bytes.length);
			return clazz;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(bis!=null) {
					bis.close();
				}
				if(bos!=null) {
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return null;
	}
}
